package com.chensi.admin.web.controller;

import com.chensi.admin.web.common.Constants;
import com.chensi.admin.web.controller.api.WebUserApi;
import com.chensi.admin.web.domain.WebUser;
import com.chensi.admin.web.dto.WebUserDTO;
import com.chensi.admin.web.dto.search.SearchWebUserDTO;
import com.chensi.admin.web.exception.BaseException;
import com.chensi.admin.web.service.WebUserService;
import com.chensi.admin.web.common.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @date 2019/6/1915:22
 */
@RestController
public class WebUserController implements WebUserApi {

    private final WebUserService webUserService;

    @Autowired
    public WebUserController(WebUserService webUserService) {
        this.webUserService = webUserService;
    }

    @Override
    public ResponseEntity<JsonResult> save(@Valid WebUser entity) throws BaseException {
        webUserService.create(entity);
        return ResponseEntity.ok(JsonResult.ok());
    }

    @Override
    @DeleteMapping("/{id}")
    public ResponseEntity<JsonResult> delete(@PathVariable("id") String id) throws BaseException {
        webUserService.delete(id);
        return ResponseEntity.ok(JsonResult.ok());
    }

    @Override
    public ResponseEntity<JsonResult<Page<WebUserDTO>>> page(SearchWebUserDTO searchWebUserDTO) throws BaseException {
        return ResponseEntity.ok(
                JsonResult.ok(
                        webUserService.page(
                                searchWebUserDTO.getUsername(),
                                searchWebUserDTO.getPageNum(),
                                searchWebUserDTO.getPageSize()
                        )
                )
        );
    }

    @Override
    public ResponseEntity<JsonResult> update(String id,@Validated({Constants.Update.class}) @RequestBody WebUser webUser) throws BaseException {
        webUserService.update(webUser);
        return ResponseEntity.ok(JsonResult.ok());
    }

    @Override
    public ResponseEntity<JsonResult<WebUserDTO>> webUser(String id) throws BaseException {
        return ResponseEntity.ok(
                JsonResult.ok(webUserService.findById(id))
        );
    }
}
